<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-12 15:23
 *
 * Version: 2.0
 */

namespace App\Modules\Employee\Services;


use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;

class AuthService extends BaseService
{
	private $userRepository;
	private $userStoreRepository;
	private $storeRepository;
	public function __construct(EmployeeRepository $employeeRepository, UserStoreRepository $userStoreRepository,StoreRepository $storeRepository)
	{
		$this->userRepository = $employeeRepository;
		$this->userStoreRepository = $userStoreRepository;
		$this->storeRepository = $storeRepository;
	}

	public function auth(){
		return $this->roles(1);
	}

	/**
	 * 用户在指定门店的角色
	 * @param $userId
	 * @param int|null  $storeId 指定门店ID 默认当前门店
	 * @return array
	 */
	public function roles($userId, $storeId=null)
	{
		return $this->userStoreRepository->roles($userId,$storeId);
	}

	/**
	 * 获取店铺信息
	 * @param $userId
	 * @param $storeId
	 * @return array|mixed
	 */
	public function store($userId,$storeId)
	{
		$isExited = $this->userStoreRepository->findWhere(['uid'=>$userId,'sid'=>$storeId]);
		if($isExited->isEmpty()) return [];
		return $this->storeRepository->find($storeId);
	}

	/**
	 * 是不是店铺创始人
	 * @param $userId
	 * @param $storeId
	 * @return bool
	 */
	public function isSuperBoss($userId,$storeId)
	{
		$storeUserId = $this->storeRepository->find($storeId,['user_id']);
		return $storeUserId == $userId ? true : false;
	}

	/**
	 * 是不是管理店长
	 * @param $userId
	 * @param $storeId
	 * @return bool
	 */
	public function isBoss($userId,$storeId)
	{
		return $this->isReal($userId,$storeId,config('constant.role.manager'),'rid');
	}

	/**
	 * 是不是常驻店
	 * @param $userId
	 * @param $storeId
	 * @return bool
	 */
	public function isHolder($userId,$storeId)
	{
		return $this->isReal($userId,$storeId,config('constant.yes'),'is_default');
	}

	/**
	 * 是不是理发师
	 * @param $userId
	 * @param $storeId
	 * @return bool
	 */
	public function isBarber($userId,$storeId)
	{
		return $this->isReal($userId,$storeId,config('constant.role.barber'),'rid');
	}

	/**
	 * 所在店铺列表
	 * @param $userId
	 * @return mixed
	 */
	public function storeList($userId)
	{
		return $this->userStoreRepository->findWhere(['uid'=>$userId]);
	}

	/**
	 * 查询StoreUser模版
	 * @param $userId
	 * @param $storeId
	 * @param $type
	 * @param $filed
	 * @return bool
	 */
	private function isReal($userId, $storeId, $type,$filed){
		$roles = $this->userStoreRepository->findWhere(['uid'=>$userId,'sid'=>$storeId],[$filed])->toArray();
		$roles = empty($roles) ? [] : array_column($roles,$filed);
		return in_array($type,$roles);
	}

}